<template>
  <div id="circleAddEdit">
    <el-dialog class="about-set" :title="title" :visible.sync="dialogData.isShow" width="700px" top="5px" :before-close="labelHandleClose">
      <div class="form-box">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="115px" class="demo-ruleForm">
          <el-form-item label="圈子名称" prop="name">
            <el-input
              v-model.trim="ruleForm.name"
              :maxlength="dialogData.nameLength"
              show-word-limit
              clearable
              :disabled="isCheck"
            ></el-input>
          </el-form-item>

          <el-form-item label="圈子说明" prop="description">
            <el-input
              v-model.trim="ruleForm.description"
              placeholder=""
              type="textarea"
              show-word-limit
              :maxlength="dialogData.desLength"
              clearable
              :disabled="isCheck"
            ></el-input>
          </el-form-item>

          <el-form-item label="圈子状态" prop="status">
            <el-radio-group v-model="ruleForm.status" :disabled="isCheck">
              <el-radio
                v-for="item in statusList"
                :key="item.dictValue"
                :label="item.dictValue"
              >
                {{ item.dictLabel }}
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="圈子头图" prop="icon">
            <uploadSingImg
              :imgUrl="ruleForm.icon"
              accept=".jpg,.jpeg,.png"
              :maxSize="2"
              @getImgUrl="getImgIcon"
              :disabled="isCheck"
            >
              <template v-slot:imgInfo>（限制上传2M以内）</template>
            </uploadSingImg>
          </el-form-item>

          <el-form-item label="包含话题" v-if="this.dialogData.type === 'check'" prop="circleTopics">
            <template v-if="ruleForm.circleTopics.length > 0">
              <el-tag
                v-for="item in ruleForm.circleTopics"
                :key="item.topicId"
                type="info"
                effect="plain">
                {{ item.topicName }}
              </el-tag>
            </template>

            <span v-else> 无 </span>
          </el-form-item>

          <el-form-item class="min-margin" label="关联学院" prop="colleges">
            <el-checkbox
              :indeterminate="collegeIsIndeterminate"
              v-model="collegeCheckAll"
              @change="collegeCheckAllChange"
              :disabled="isCheck">
                全选
            </el-checkbox>

            <div style="margin: 9px 0;"></div>
            
            <el-checkbox-group v-model="ruleForm.colleges" @change="collegeCheckedChange" :disabled="isCheck">
              <el-checkbox
                v-for="(item, index) in collegeList"
                :label="item.dictValue"
                :key="index">
                  {{ item.dictLabel }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>

        <h3 class="list-title">添加显性标签</h3>

        <el-form ref="formInline" :inline="true" :model="formInline" :rules="rulesInline" class="demo-form-inline">
          <el-form-item label="选择分类" prop="classifiName">
            <el-select v-model="formInline.classifiName" filterable placeholder="请选择" value-key="id">
              <el-option
                v-for="item in classifiNameList"
                :key="item.id"
                :label="item.labelCategoryName"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="选择标签名称" prop="labelName">
            <el-select v-model="formInline.labelName" filterable placeholder="请选择" value-key="id">
              <el-option v-for="item in labelNameList" :key="item.id" :label="`${item.labelName}-${item.id}`" :value="item">{{ item.labelName }}-{{ item.id }}</el-option>
            </el-select>
          </el-form-item>

          <el-button class="button" type="success" @click="handAdd('show')" :disabled="isCheck">添加</el-button>
        </el-form>

        <!-- 表格部分 -->
        <el-table :data="tableData" style="width: 100%" height="320">
          <el-table-column
            type="index"
            width="60"
            align="center"
            label="序号"
          ></el-table-column>

          <el-table-column
            label="分类名"
            prop="tagCategoryName"
            width="160"
          ></el-table-column>

          <el-table-column label="标签名+ID" prop="labelName" min-width="150">
            <template slot-scope="{ row }">
              {{ row.labelName }}-{{ row.id }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-button type="text" @click="delLine(scope.$index, 'show')" :disabled="isCheck">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <h3 class="list-title">添加隐性标签</h3>
        
        <el-form ref="hideFormInline" :inline="true" :model="hideFormInline" class="demo-form-inline">
          <el-form-item label="选择分类" prop="classifiName">
            <el-select
              v-model="hideFormInline.classifiName"
              filterable
              placeholder="请选择"
              value-key="id"
            >
              <el-option
                v-for="item in hideClassifiNameList"
                :key="item.id"
                :label="item.labelCategoryName"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="选择标签名称" prop="labelName">
            <el-select v-model="hideFormInline.labelName" filterable placeholder="请选择" value-key="id">
              <el-option v-for="item in hideLabelNameList" :key="item.id" :label="`${item.labelName}-${item.id}`" :value="item">{{ item.labelName }}-{{ item.id }}</el-option>
            </el-select>
          </el-form-item>

          <el-button
            class="button"
            type="success"
            @click="handAdd('hide')"
            :disabled="isCheck"
          >
            添加
          </el-button>
        </el-form>

        <!-- 表格部分 -->
        <el-table :data="hideTableData" style="width: 100%" height="320">
          <el-table-column
            type="index"
            width="60"
            align="center"
            label="序号"
          ></el-table-column>

          <el-table-column
            label="分类名"
            prop="tagCategoryName"
            width="160"
          ></el-table-column>

          <el-table-column label="标签名+ID" prop="labelName" min-width="150">
            <template slot-scope="{ row }">
              {{ row.labelName }}-{{ row.id }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="delLine(scope.$index, 'hide')"
                :disabled="isCheck"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="cancelLabel">取 消</el-button>
        <el-button v-if="!isCheck" type="success" :loading="loading" @click="confirmLabel('ruleForm')">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { sysNormalDisable } from '@utils/dictionariesFunc'
import { getClasses, getLabels } from '@/api/contentTags/configureTag' // 接口
import { addCircle, circleInfoById, editCircle } from '@/api/circle/circleManage' // 接口
import uploadSingImg from '@common/uploadSingImg' // 上传单个图片公共组件

export default {
  name: 'circleAddEdit',
  msg: '圈子管理-新增/编辑/查看弹窗',
  props: ['dialogData', 'maxLabelNum'],
  components: {
    uploadSingImg
  },
  data() {

    const collegesValidate = (rule, value, callback) => {
      const { colleges } = this.ruleForm
      if (colleges.length === 0 && this.enterSubmit) {
        callback(new Error('请至少选择一个关联学院'))
      } else {
        callback()
      }
    }

    return {
      loading: false,
      id: '',
      isAdd: true, //是否新增
      isCheck: false, //是否查看
      title: '',
      attrList: {}, //属性对象
      statusList: [], // 圈子状态
      classifiNameList: [], //显性标签-选择分类
      labelNameList: [], //显性标签-标签名称
      hideClassifiNameList: [], //隐性标签-选择分类
      hideLabelNameList: [], //隐性标签-标签名称
      defaultClassifiName: {
        //默认值
        labelCategoryName: '-- 请选择标签分类 --',
        id: ''
      },
      defaultLabelName: {
        //默认值
        labelName: '-- 请选择标签名 --',
        id: ''
      },
      ruleForm: {
        status: '', // 圈子状态
        name: '', //圈子名称
        description: '', //圈子说明
        icon: '', //圈子头图
        colleges: [], // 选中学院
        circleTopics: [] // 圈子包含的话题
      },
      formInline: {
        //显性标签
        classifiName: {}, //选择分类
        labelName: {} //标签名称
      },
      hideFormInline: {
        //隐形标签
        classifiName: {}, //选择分类
        labelName: {} //标签名称
      },
      rules: {
        status: {
          required: true,
          message: '请选择圈子状态',
          trigger: 'blur'
        },
        name: {
          required: true,
          message: '您没有填写圈子名称',
          trigger: 'blur'
        },
        icon: {
          required: true,
          message: '您没有上传圈子头图',
          trigger: 'change'
        },
        colleges: {
          required: true,
          validator: collegesValidate,
          trigger: 'change'
        }
      },
      enterSubmit: false,
      rulesInline: {},
      tableData: [],
      hideTableData: [],
      collegeIsIndeterminate: false,
      collegeCheckAll: false,
      collegeList: [],
      allCollegeId: []
    }
  },
  watch: {
    'formInline.classifiName': {
      //标签分类
      handler(newVal, oldVal) {
        this.labelNameList = [this.defaultLabelName]
        this.formInline.labelName = this.defaultLabelName
        if (newVal.id) {
          //标签名
          this.getNameList(newVal.id, 'show')
        }
      },
      deep: true
    },
    'hideFormInline.classifiName': {
      //标签分类
      handler(newVal, oldVal) {
        this.hideLabelNameList = [this.defaultLabelName]
        this.hideFormInline.labelName = this.defaultLabelName
        if (newVal.id) {
          //标签名
          this.getNameList(newVal.id, 'hide')
        }
      },
      deep: true
    }
  },
  mounted() {
    switch (this.dialogData.type) {
      case 'add':
        this.isAdd = true
        this.title = '创建圈子'
        break
      case 'edit':
        this.isAdd = false
        this.title = '编辑圈子'
        break
      case 'check':
        this.isAdd = false
        this.isCheck = true
        this.title = '查看圈子'
        break
    }
    this.getStateList()
    this.setDefault()
    this.getClassList()
    this.getHideClassList()
  },
  methods: {
    async getStateList() {
      // 圈子状态
      this.statusList = await sysNormalDisable('circle_status')
      // 学院
      this.collegeList = await sysNormalDisable('sys_college', 'circleCollege')
      this.getAllCollegeId()
      if (this.isAdd) {
        //新增
        this.ruleForm.status = this.statusList[0].dictValue
      } else {
        //编辑
        this.getFormData()
      }
    },
    /*编辑-获取表单详情*/
    getFormData() {
      this.id = this.dialogData.id
      circleInfoById(this.id, (res) => {
          let { basicInfo: { name, description, icon, colleges }, status, circleTopics } = res
          this.ruleForm = { name, description, icon, status, colleges, circleTopics }

          //关联学院-全选按钮
          this.collegeCheckedChange(colleges)

          //获取table数据
          let ary = res.basicInfo.recommendTags
          ary.forEach((item) => {
            let obj = {
              tagCategoryName: item.labelCategoryName, //分类名
              labelName: item.name, //标签名称
              id: item.id //标签id
            }
            this.tableData.push(obj)
          })
          //获取hideTableData数据
          let aryHide = res.invisibilityTags
          aryHide.forEach((item) => {
            let obj = {
              tagCategoryName: item.labelCategoryName, //分类名
              labelName: item.name, //标签名称
              id: item.id //标签id
            }
            this.hideTableData.push(obj)
          })
        },
        (response) => {
          this.$message.warning(response.message)
        }
      )
    },
    /*设置默认值*/
    setDefault() {
      //显性-标签分类
      this.classifiNameList = [this.defaultClassifiName]
      this.formInline.classifiName = this.defaultClassifiName
      //显性-标签名
      this.labelNameList = [this.defaultLabelName]
      this.formInline.labelName = this.defaultLabelName
      //隐性-标签分类
      this.hideClassifiNameList = [this.defaultClassifiName]
      this.hideFormInline.classifiName = this.defaultClassifiName
      //隐性-标签名
      this.hideLabelNameList = [this.defaultLabelName]
      this.hideFormInline.labelName = this.defaultLabelName
    },
    //圈子头图设置
    getImgIcon(url) {
      this.ruleForm.icon = url
      this.$refs['ruleForm'].clearValidate(['icon'])
    },
    
    /*获取显性标签-分类列表*/
    getClassList() {
      let obj = {
        labelCategoryProperty: 'SHOW_TAG'
      }
      getClasses(
        obj,
        (response) => {
          this.classifiNameList = [this.defaultClassifiName, ...response]
        },
        (response) => {
          this.$message.warning(response.message)
        }
      )
    },
    /*获取隐性标签-分类列表*/
    getHideClassList() {
      let obj = {
        labelCategoryProperty: 'HIDING_TAG'
      }
      getClasses(
        obj,
        (response) => {
          this.hideClassifiNameList = [this.defaultClassifiName, ...response]
        },
        (response) => {
          this.$message.warning(response.message)
        }
      )
    },
    /*获取显性标签-名称列表*/
    getNameList(id, type) {
      let listName = type === 'hide' ? 'hideLabelNameList' : 'labelNameList'
      let obj = {
        isRecommend: true
      }
      getLabels(
        id,
        obj,
        (response) => {
          this[listName] = [this.defaultLabelName, ...response]
        },
        (response) => {
          this.$message.warning(response.message)
        }
      )
    },
    /*选中标签添加到 table 中*/
    handAdd(type) {
      let tableName = type === 'show' ? 'tableData' : 'hideTableData'
      let formName = type === 'show' ? 'formInline' : 'hideFormInline'
      if (type === 'show' && this[tableName].length >= this.maxLabelNum) {
        this.$message.warning(`最多选择${this.maxLabelNum}个标签`)
        return
      }
      if (type === 'hide' && this[tableName].length >= 50) {
        this.$message.warning(`最多选择50个标签`)
        return
      }
      if (!this[formName].labelName || !this[formName].labelName.id) {
        return
      }
      let curTags = this[formName].labelName
      let i = this[tableName].findIndex(
        (item) => item.id.toString() === curTags.id
      )
      //数据重复，不允许加入this.tableData || this.hideTableData
      if (i >= 0) {
        this.$message.warning('该数据已存在列表中!')
        return
      }
      let curObj = { ...this[formName] }
      // console.log(curObj)
      let obj = {
        tagCategoryName: curObj.classifiName.labelCategoryName, //分类名
        labelName: curObj.labelName.labelName, //标签名称
        id: curObj.labelName.id //标签id
      }
      this[tableName].push(obj)
    },
    /*删除*/
    delLine(i, type) {
      let tableName = type === 'show' ? 'tableData' : 'hideTableData'
      this.$confirm('确定移除标签吗？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this[tableName].splice(i, 1)
        })
        .catch(() => {})
    },
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    cancelLabel() {
      // 关闭前清空
      this.enterSubmit = false
      this.loading = false
      this.dialogData.id = ''
      this.dialogData.row = {}
      this.dialogData.isShow = false
    },
    getLabelIds(type) {
      let ary = []
      if (type === 'show') {
        this.tableData.forEach((item) => {
          ary.push({ id: item.id })
        })
      } else {
        this.hideTableData.forEach((item) => {
          ary.push(item.id)
        })
      }
      return [...ary]
    },
    /* 确认提交 */
    confirmLabel(formName) {

      this.enterSubmit = true

      //选中的隐性标签
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let recommendTags = this.getLabelIds('show')
          //选中的隐性标签
          let invisibilityTags = this.getLabelIds('hide')
          /*if (recommendTags.length === 0) {
            this.$message.warning('请添加标签！')
            return
          }*/
          this.loading = true
          let obj = { ...this.ruleForm, recommendTags, invisibilityTags }
          if (this.isAdd) {
            //新增
            addCircle(
              obj,
              (response) => {
                this.$emit('refresh')
                this.cancelLabel()
              },
              (response) => {
                this.$message.warning(response.message)
                this.loading = false
              }
            )
          } else {
            //编辑
            editCircle(
              this.dialogData.id,
              obj,
              (response) => {
                this.$message.success('操作成功')
                this.$emit('refresh')
                this.cancelLabel()
              },
              (response) => {
                this.$message.warning(response.message)
                this.loading = false
              }
            )
          }
        } else {
          return false
        }
      })
    },
    /* 全选、全不选 */
    collegeCheckAllChange(val) {
      this.ruleForm.colleges = val ? this.allCollegeId : []
      this.collegeIsIndeterminate = false
    },
    /* 选中学院checkbox发生变化 */
    collegeCheckedChange(value) {
      let checkedCount = value.length
      this.collegeCheckAll = checkedCount === this.allCollegeId.length
      this.collegeIsIndeterminate = checkedCount > 0 && checkedCount < this.allCollegeId.length
    },
    /*获取全部学院id*/
    getAllCollegeId() {
      let ary = []
      this.collegeList.forEach((item) => {
        if (item.dictValue) {
          ary.push(item.dictValue)
        }
      })
      this.allCollegeId = [...ary]
    }
  }
}
</script>

<style lang="less">
@import url('~@common/style/textarea.less');
#circleAddEdit {
  .el-textarea__inner {
    height: 70px;
  }
  .list-title {
    font-size: 15px;
    color: #333;
    font-weight: bold;
    line-height: 20px;
    padding-bottom: 10px;
    margin: 12px 0;
    border-bottom: 1px solid #eee;
  }
  .demo-form-inline {
    .el-form-item__content {
      width: 184px;
    }
    .el-button {
      margin-top: 6px;
    }
  }
  .el-table {
    margin-bottom: 20px;
  }
  .min-margin {
    .el-form-item__content {
      padding-top: 10px;
      line-height: 20px;
    }
  }
}
</style>
